package exams.huawei;

import java.util.*;
import java.util.concurrent.*;
import java.util.random.RandomGenerator;

import static java.lang.Thread.sleep;

public class Main {


    /**
     * 初始化10个任务 每个任务有耗时，整数1-5 随机生成
     * 启动2个线程完成 所有任务，求最短时间
     * */

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Random random = new Random();
        List<Integer> taskList = new ArrayList<>();
        for(int i =0; i<10; i++) {
            taskList.add(Math.abs(random.nextInt() % 5) + 1);
        }
        List<Long> timeList = new ArrayList<>();
        int sum = 0;
        for(Integer v: taskList) {
            sum += v;
        }
        int target = sum / 2;
        taskList.sort(Comparator.naturalOrder());
        int p = 0;
        int dSum = 0;
        while (dSum < target) {
            dSum += taskList.get(p);
            p++;
        }


    Executors.newSingleThreadExecutor();

        ExecutorService executorService = Executors.newFixedThreadPool(2);

        for(Integer task: taskList) {
            Future<Long> future = executorService.submit(() -> {
                return doTask(task);
            });
            timeList.add(future.get() / 1000);
        }
        long res = 0;
        for(long time: timeList) {
            if(time > res) {
                res = time;
            }
        }
        System.out.println(res);
        executorService.shutdown();
    }

     public static long doTask(int value) {
         long startTime = getCurrentTime();
         try {
             sleep(value * 1000);
             System.out.println("Thread " + Thread.currentThread().getName() + " spent " + value + " done.");
         } catch (InterruptedException e) {
             throw new RuntimeException(e);
         }
         long endTime = getCurrentTime();
         return endTime - startTime;
     }

     public static long getCurrentTime() {
         Date date = new Date();
         return date.getTime();
     }
}